<template>
  <div class="bg-gray-800 rounded-lg p-4">
    <h3 class="text-lg font-medium mb-4">{{ isEditing ? '编辑模型' : '添加自定义模型' }}</h3>
    
    <form @submit.prevent="saveModel" class="space-y-4">
      <div>
        <label class="block text-sm text-gray-400 mb-1">模型名称</label>
        <input 
          v-model="modelData.name"
          type="text" 
          placeholder="例如: GPT-4"
          class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
          required
        />
      </div>
      
      <div>
        <label class="block text-sm text-gray-400 mb-1">提供商</label>
        <select 
          v-model="modelData.provider"
          class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
          required
        >
          <option value="">选择提供商</option>
          <option v-for="provider in providers" :key="provider.id" :value="provider.id">
            {{ provider.name }}
          </option>
          <option value="custom">自定义</option>
        </select>
      </div>
      
      <div v-if="modelData.provider === 'custom'">
        <label class="block text-sm text-gray-400 mb-1">自定义提供商名称</label>
        <input 
          v-model="modelData.customProvider"
          type="text" 
          placeholder="例如: Cohere"
          class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
          required
        />
      </div>
      
      <div>
        <label class="block text-sm text-gray-400 mb-1">API 密钥</label>
        <div class="flex space-x-2">
          <select 
            v-model="modelData.apiKeyId"
            class="flex-1 bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
            required
          >
            <option value="">选择 API 密钥</option>
            <option v-for="apiKey in apiKeys" :key="apiKey.id" :value="apiKey.id">
              {{ apiKey.provider }} - {{ maskApiKey(apiKey.key) }}
            </option>
          </select>
          <button 
            type="button"
            @click="showAddCustomKey = true"
            class="px-3 py-2 bg-gray-700 hover:bg-gray-600 rounded-md text-sm"
            title="添加自定义密钥"
          >
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
            </svg>
          </button>
        </div>
      </div>
      
      <div>
        <label class="block text-sm text-gray-400 mb-1">模型 ID</label>
        <input 
          v-model="modelData.modelId"
          type="text" 
          placeholder="例如: gpt-4-turbo"
          class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
          required
        />
      </div>
      
      <div v-if="selectedApiKey && selectedApiKey.isCustom">
        <div class="text-sm text-gray-400">
          <p class="font-medium">所选API密钥配置:</p>
          <ul class="list-disc list-inside mt-2 text-xs space-y-1">
            <li>端点: {{ selectedApiKey.endpoint }}</li>
            <li v-if="selectedApiKey.ignoreV1">忽略v1版本路径</li>
            <li v-if="selectedApiKey.forceUseInput">强制使用输入地址</li>
            <li v-if="selectedApiKey.modelName">预设模型: {{ selectedApiKey.modelName }}</li>
          </ul>
        </div>
      </div>
      
      <div>
        <label class="block text-sm text-gray-400 mb-1">描述</label>
        <textarea 
          v-model="modelData.description"
          placeholder="模型的简短描述..."
          class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
          rows="3"
        ></textarea>
      </div>
      
      <div>
        <label class="block text-sm text-gray-400 mb-1">图标文本</label>
        <input 
          v-model="modelData.iconText"
          type="text" 
          placeholder="例如: G4"
          class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
          maxlength="2"
        />
        <p class="mt-1 text-xs text-gray-500">最多 2 个字符，显示在模型图标中</p>
      </div>
      
      <div>
        <label class="block text-sm text-gray-400 mb-1">图标颜色</label>
        <div class="flex space-x-2 mt-1">
          <div 
            v-for="color in iconColors" 
            :key="color.value"
            @click="modelData.iconBg = color.value"
            :class="[
              'w-8 h-8 rounded-full cursor-pointer transition-transform hover:scale-110',
              color.value,
              modelData.iconBg === color.value ? 'ring-2 ring-white ring-offset-2 ring-offset-gray-800' : ''
            ]"
          ></div>
        </div>
      </div>
      
      <div class="pt-4 flex justify-end space-x-3">
        <button 
          type="button"
          @click="cancel"
          class="px-4 py-2 bg-gray-700 hover:bg-gray-600 rounded-md transition-colors"
        >
          取消
        </button>
        <button 
          type="submit"
          class="px-4 py-2 bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white rounded-md hover:opacity-90 transition-opacity"
        >
          {{ isEditing ? '保存更改' : '添加模型' }}
        </button>
      </div>
    </form>
    
    <!-- 添加自定义密钥弹窗 -->
    <div v-if="showAddCustomKey" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-gray-800 rounded-lg p-6 w-96 max-w-full">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-medium">添加自定义密钥</h3>
          <button @click="showAddCustomKey = false" class="text-gray-400 hover:text-white">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        
        <div class="space-y-4">
          <div>
            <label class="block text-sm text-gray-400 mb-1">API 密钥</label>
            <input 
              v-model="newApiKey.key"
              type="text" 
              class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
              placeholder="sk-xxxxxxxx"
            />
          </div>
          
          <div>
            <label class="block text-sm text-gray-400 mb-1">API 地址</label>
            <input 
              v-model="newApiKey.endpoint"
              type="text" 
              class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
              placeholder="https://example.com/api/"
            />
            
            <div class="mt-1 text-xs text-gray-400">
              <div>* 地址以 / 结尾: 忽略v1版本路径</div>
              <div>* 地址以 # 结尾: 强制使用输入的地址</div>
            </div>
          </div>
          
          <div>
            <label class="block text-sm text-gray-400 mb-1">模型名称</label>
            <input 
              v-model="newApiKey.modelName"
              type="text" 
              class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
              placeholder="填写要使用的模型名称"
            />
          </div>
          
          <div>
            <label class="block text-sm text-gray-400 mb-1">模型ID</label>
            <input 
              v-model="newApiKey.provider"
              type="text" 
              class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 focus:outline-none focus:ring-2 focus:ring-[#8153ff] focus:border-transparent"
              placeholder="填写对应服务提供商的模型ID"
            />
          </div>
        </div>
        
        <div class="mt-6 flex space-x-2">
          <button 
            @click="showAddCustomKey = false"
            class="flex-1 py-2 bg-gray-700 hover:bg-gray-600 rounded-lg"
          >
            取消
          </button>
          <button 
            @click="addNewApiKey"
            class="flex-1 py-2 bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white rounded-lg hover:opacity-90"
            :disabled="!isValidNewApiKey"
          >
            添加
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, computed } from 'vue';

const props = defineProps({
  model: {
    type: Object,
    default: null
  },
  apiKeys: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['save', 'cancel', 'add-api-key']);

// 是否为编辑模式
const isEditing = ref(!!props.model);

// 模型数据
const modelData = ref({
  name: props.model?.name || '',
  provider: props.model?.provider || '',
  customProvider: props.model?.customProvider || '',
  apiKeyId: props.model?.apiKeyId || '',
  modelId: props.model?.modelId || '',
  description: props.model?.description || '',
  iconText: props.model?.iconText || 'AI',
  iconBg: props.model?.iconBg || 'bg-[#8153ff]'
});

// 选中的API密钥
const selectedApiKey = computed(() => {
  if (!modelData.value.apiKeyId) return null;
  return props.apiKeys.find(key => key.id === modelData.value.apiKeyId);
});

// 自定义密钥弹窗状态
const showAddCustomKey = ref(false);

// 新API密钥表单
const newApiKey = ref({
  provider: '',
  key: '',
  endpoint: '',
  modelName: ''
});

// 验证新API密钥是否有效
const isValidNewApiKey = computed(() => {
  return newApiKey.value.key.trim() !== '' && 
         newApiKey.value.endpoint.trim() !== '' && 
         newApiKey.value.provider.trim() !== '';
});

// API提供商列表
const providers = [
  { id: 'openai', name: 'OpenAI' },
  { id: 'anthropic', name: 'Anthropic' },
  { id: 'google', name: 'Google AI' },
  { id: 'mistral', name: 'Mistral AI' },
  { id: 'azure', name: 'Azure OpenAI' }
];

// 图标颜色选项
const iconColors = [
  { value: 'bg-[#8153ff]', name: '藤紫' },
  { value: 'bg-[#93dc24]', name: '钛啡绿' },
  { value: 'bg-blue-500', name: '蓝色' },
  { value: 'bg-green-500', name: '绿色' },
  { value: 'bg-red-500', name: '红色' },
  { value: 'bg-yellow-500', name: '黄色' },
  { value: 'bg-purple-500', name: '紫色' },
  { value: 'bg-gray-500', name: '灰色' }
];

// 掩码显示API密钥
const maskApiKey = (key) => {
  if (!key) return '';
  const prefix = key.substring(0, 3);
  const suffix = key.substring(key.length - 4);
  return `${prefix}...${suffix}`;
};

// 处理自定义API密钥的地址格式
const processEndpoint = (endpoint) => {
  const trimmedEndpoint = endpoint.trim();
  
  // 如果以/结尾
  if (trimmedEndpoint.endsWith('/')) {
    return {
      processedEndpoint: trimmedEndpoint,
      ignoreV1: true,
      forceUseInput: false
    };
  } 
  // 如果以#结尾
  else if (trimmedEndpoint.endsWith('#')) {
    return {
      processedEndpoint: trimmedEndpoint.slice(0, -1), // 移除#
      ignoreV1: false,
      forceUseInput: true
    };
  } 
  // 正常情况
  else {
    return {
      processedEndpoint: trimmedEndpoint,
      ignoreV1: false,
      forceUseInput: false
    };
  }
};

// 添加新的自定义API密钥
const addNewApiKey = () => {
  if (!isValidNewApiKey.value) return;
  
  const { processedEndpoint, ignoreV1, forceUseInput } = processEndpoint(newApiKey.value.endpoint);
  
  // 创建新的API密钥对象
  const newKey = {
    id: `custom-${Date.now()}`, // 生成唯一ID
    provider: newApiKey.value.provider,
    key: newApiKey.value.key,
    endpoint: processedEndpoint,
    modelName: newApiKey.value.modelName,
    ignoreV1: ignoreV1,
    forceUseInput: forceUseInput,
    showKey: false,
    editing: false,
    isCustom: true
  };
  
  // 触发添加API密钥事件
  emit('add-api-key', newKey);
  
  // 设置新添加的密钥为当前选中的密钥
  modelData.value.apiKeyId = newKey.id;
  
  // 重置表单并关闭弹窗
  newApiKey.value = {
    provider: '',
    key: '',
    endpoint: '',
    modelName: ''
  };
  
  showAddCustomKey.value = false;
};

// 保存模型配置
const saveModel = () => {
  const formData = { ...modelData.value };
  
  // 如果是自定义提供商，使用用户输入的名称
  if (formData.provider === 'custom' && formData.customProvider) {
    formData.providerName = formData.customProvider;
  } else {
    const provider = providers.find(p => p.id === formData.provider);
    formData.providerName = provider ? provider.name : formData.provider;
  }
  
  // 如果选中的API密钥有预设的模型名称，优先使用它
  if (selectedApiKey.value && selectedApiKey.value.modelName && !formData.modelId) {
    formData.modelId = selectedApiKey.value.modelName;
  }
  
  // 确保modelName字段包含modelId的值，以便正确显示
  formData.modelName = formData.modelId;
  
  emit('save', formData);
};

// 取消操作
const cancel = () => {
  emit('cancel');
};
</script>

<style scoped>
</style> 